<!-- 登录 -->
<template>
  <SimpleHeaderbar />
  <div id="container" class="flex justify-center">
    <div id="login-form">
      <div class="big-text">欢迎回来</div>
      <!-- <div class="small-text">
        我们将通过邮箱来判断您的科研机构,并帮助您找到您的同事。
      </div> -->
      <n-form ref="formRef" :model="model">
        <n-form-item path="email" label="邮箱" :label-style="labelStyle">
          <n-input v-model:value="model.email" @keydown.enter.prevent />
        </n-form-item>
        <n-form-item path="password" label="密码" :label-style="labelStyle">
          <n-input
            v-model:value="model.password"
            type="password"
            @keydown.enter.prevent="handleLoginClick"
          />
        </n-form-item>

        <n-row :gutter="[0, 24]">
          <n-col :span="24">
            <div style="display: flex; justify-content: flex-end">
              <n-button
                quaternary
                type="primary"
                size="tiny"
                style="position: relative; bottom: -10px"
                @click="handleForgetClick"
              >
                忘记密码？
              </n-button>
              <n-button round type="primary" @click="handleLoginClick">
                登录
              </n-button>
            </div>
          </n-col>
        </n-row>
        <div class="register-box">
          <span class="small-text">没有账号？</span>
          <n-button
            quaternary
            type="primary"
            size="small"
            style="position: relative; bottom: -4px"
            @click="router.push('/register')"
          >
            注册
          </n-button>
        </div>
      </n-form>
    </div>
  </div>
  <!-- 忘记密码的弹窗 -->
  <n-modal
    v-model:show="showForgetModal"
    :mask-closable="false"
    preset="dialog"
    :on-after-leave="closeForgetModal"
    class="forget-modal"
  >
    <template #header>
      <div>忘记密码</div>
    </template>
    <div class="label-text">
      请输入邮箱：
      <n-input
        v-model:value="model.email"
        placeholder="邮箱"
        size="small"
        :disabled="codeConfirmed"
      />
      <div class="code-button">
        <n-button
          :disabled="
            !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(
              model.email
            ) ||
            codeSent ||
            codeConfirmed
          "
          type="primary"
          @click="handleCodeSend"
          size="tiny"
          v-if="!codeSent"
        >
          发送验证码
        </n-button>
        <n-button
          :disabled="
            !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(
              model.email
            ) || codeSent
          "
          type="primary"
          size="tiny"
          v-if="codeSent"
        >
          {{ leftTime }}
        </n-button>
      </div>
    </div>
    <div class="label-text">
      请输入验证码:
      <n-input
        v-model:value="model.identifyCode"
        placeholder="验证码"
        size="small"
        :maxlength="6"
        :on-input="codeUpdate"
        :loading="isverifying"
        :disabled="codeConfirmed"
      />
    </div>
    <n-form
      :model="forgetModel"
      :rules="rules"
      ref="formRef"
      v-if="codeConfirmed"
    >
      <n-grid :cols="2" :x-gap="0" class="password-box">
        <n-form-item-gi
          path="password"
          label="新密码"
          :label-style="labelStyle"
        >
          <n-input
            v-model:value="forgetModel.password"
            type="password"
            @keydown.enter.prevent
          />
        </n-form-item-gi>
        <n-form-item-gi
          ref="rPasswordFormItemRef"
          first
          path="reenteredPassword"
          label="重复密码"
          :label-style="labelStyle"
        >
          <n-input
            v-model:value="forgetModel.reenteredPassword"
            :disabled="!forgetModel.password"
            type="password"
            @keydown.enter.prevent
          />
        </n-form-item-gi>
      </n-grid>
      <div class="code-button">
        <n-button @click="handlerResetClick" type="primary" size="small">
          重置密码
        </n-button>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import SimpleHeaderbar from '../../components/common/SimpleHeaderbar.vue'
import api from '@/api/api'
const { Entry } = api

const formRef = ref(null)
const message = useMessage()
const router = useRouter()

//忘记密码弹窗
const showForgetModal = ref(false)
//已经发送验证码
const codeSent = ref(false)
//验证码验证中
const isverifying = ref(false)
//验证码发送后的倒计时
const leftTime = ref(30)
const handleCodeSend = function () {
  codeSent.value = true
  const parmas = {
    email: model.value.email
  }
  Entry.resetCode(parmas)
    .then((res) => {
      if (res.success) {
        message.success('验证码已发送')
        var timer = setInterval(() => {
          leftTime.value--
          if (leftTime.value == 0) {
            stopTimer()
          }
        }, 1000)
        function stopTimer() {
          leftTime.value = 30
          clearInterval(timer)
          codeSent.value = false
        }
      } else {
        message.error('验证码发送失败')
        message.error(res.result)
      }
    })
    .catch((err) => {
      message.error('验证码发送失败', err)
    })
}
//验证码被确定
const codeConfirmed = ref(false)
const codeUpdate = function (value) {
  if (value.length === 6) {
    isverifying.value = true
    //调接口
    Entry.codeverify({
      email: model.value.email,
      identifyCode: model.value.identifyCode
    })
      .then((res) => {
        if (res.success) {
          codeConfirmed.value = true
          message.success('验证成功')
        } else {
          message.error(res.result)
        }
        isverifying.value = false
      })
      .catch((res) => {
        message.error('验证出现错误', res)
        isverifying.value = false
      })
  }
}
//忘记密码表单
const forgetModel = ref({
  password: '',
  reenteredPassword: ''
})
//忘记表单---密码验证规则
const rules = {
  password: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入密码')
        } else if (!/^[\w]{6,20}$/.test(value)) {
          return new Error('密码要求6~20位')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  reenteredPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input'
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }
  ]
}
function validatePasswordStartWith(rule, value) {
  return (
    !!forgetModel.value.password &&
    forgetModel.value.password.startsWith(value) &&
    forgetModel.value.password.length >= value.length
  )
}
function validatePasswordSame(rule, value) {
  return value === forgetModel.value.password
}
//关掉忘记密码弹窗
const closeForgetModal = function () {
  showForgetModal.value = false
  model.value.email = ''
  model.value.identifyCode = ''
  codeConfirmed.value = false
  forgetModel.value.password = ''
  forgetModel.value.reenteredPassword = ''
}
//重置密码
const handlerResetClick = function (e) {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      let params = {
        email: model.value.email,
        password: forgetModel.value.password,
        identifyCode: model.value.identifyCode
      }
      Entry.resetPassword(params)
        .then((res) => {
          if (res.success) {
            message.success('重置成功')
            showForgetModal.value = false
            model.value.email = ''
            model.value.identifyCode = ''
            forgetModel.value.password = ''
            forgetModel.value.reenteredPassword = ''
            codeConfirmed.value = false
          } else {
            message.error('发生错误')
          }
        })
        .catch((err) => {
          message.error('出现错误')
          console.log('error:', err)
        })
    } else {
      console.log(errors)
      message.error('请检查参数')
    }
  })
}

//登录表单
const model = ref({
  email: '',
  password: '',
  identifyCode: ''
})
//登录
const handleLoginClick = function () {
  const param = {
    email: model.value.email,
    password: model.value.password
  }
  Entry.login(param)
    .then((res) => {
      if (res.success) {
        message.success('登录成功')
        localStorage.setItem('name', res.name)
        localStorage.setItem('avatar', res.avatar)
        localStorage.setItem('isLogin', true)
        localStorage.setItem('id', res.id)
        router.push('/homepage')
      } else {
        message.error(res.msg)
      }
    })
    .catch((err) => {
      message.error('出现错误', err)
    })
}

//表单label的样式
const labelStyle = {
  fontSize: '.975rem',
  fontWeight: '400',
  color: '#87827c'
}

//忘记密码
const handleForgetClick = function () {
  showForgetModal.value = true
}

onMounted(() => {})
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  min-height: calc(100vh - 73px);
  background-color: #f4f4f4;
  margin-top: 72px;
}

#login-form {
  width: 400px;

  .big-text {
    font-family: 'Roboto', Arial, sans-serif;
    font-weight: 400;
    font-size: 1.375rem;
    line-height: 1.2;
    color: #333;
    text-align: center;
    margin-top: 3vh;
    margin-bottom: 2vh;
  }

  .register-box {
    display: flex;
    justify-content: center;
    align-items: flex-end;

    .small-text {
      font-size: 0.875rem;
      font-weight: 400;
      color: #777;
      line-height: 1.5;
      text-align: center;
    }
  }
}

.forget-modal {
  .label-text {
    font-size: 0.875rem;
    font-weight: 400;
    color: #87827c;
  }

  .n-input {
    max-width: 75%;
  }

  .password-box {
    margin-top: 15px;

    .n-input {
      max-width: 97%;
    }
  }

  .code-button {
    margin: 1vh 9px 1vh 0;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
